package com.lensyn.generator.plugins;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;
import java.util.Properties;

public class GeneratedKeyPlugin extends PluginAdapter {

    public boolean validate(List<String> warnings) {
        return true;
    }


    boolean autoGenPK;

    public void setProperties(Properties properties) {
      String genPK =  properties.getProperty("GeneratedValueAnnotation","true");

        autoGenPK = Boolean.valueOf(genPK);

    }
    @Override
    public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {



        boolean isPK = introspectedTable.getPrimaryKeyColumns().stream().anyMatch(t ->{
            return t.getActualColumnName().equals(introspectedColumn.getActualColumnName());
        });

        boolean autoInc = introspectedColumn.isIdentity()||introspectedColumn.isAutoIncrement();


        if(autoInc&&isPK&&autoGenPK){

            field.addAnnotation("@GeneratedValue(strategy = GenerationType.IDENTITY)");
        }

        return super.modelFieldGenerated(field, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
    }
}
